<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>我的历史订单</title>
    <link href="/home/css/common.css" rel="stylesheet" type="text/css"/>
    <link href="/home/css/style.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="/home/js/axios.js"></script>
    <script type="text/javascript" src="/home/js/config.js"></script>
    <script type="text/javascript" src="/home/js/vue.js"></script>
    <style>
        .search-container {
            background: #f5f5f5;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .search-item {
            margin-right: 20px;
            display: inline-block;
            margin-bottom: 10px;
        }

        .search-item label {
            margin-right: 8px;
            color: #666;
            font-size: 14px;
        }

        .search-item input,
        .search-item select {
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            width: 180px;
            height: 40px;
            box-sizing: border-box;
        }

        .search-item input:focus,
        .search-item select:focus {
            border-color: #3480e2;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 128, 226, 0.2);
        }

        .btn-search {
            background: #3480e2;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            height: 40px;
            margin-right: 10px;
        }

        .btn-reset {
            background: #909399;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            height: 40px;
        }

        .btn-reset:hover {
            background: #7d8087;
            transform: translateY(-1px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .btn-reset:active {
            transform: translateY(0);
            box-shadow: none;
        }

        .order-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            table-layout: fixed;
        }

        .order-table th, .order-table td {
            padding: 14px 16px;
            text-align: left;
            border-bottom: 1px solid #eee;
            word-wrap: break-word;
            overflow: hidden;
            box-sizing: border-box;
        }

        .order-table th {
            background: #f5f7fa;
            color: #333;
            font-weight: 600;
            position: sticky;
            top: 0;
            z-index: 1;
            border-bottom: 2px solid #e1e5eb;
            width: 20%;
        }

        .order-table tbody tr {
            transition: background-color 0.2s ease;
        }

        .order-table tbody tr:hover {
            background-color: #f9fafc;
        }

        .order-table tbody tr:nth-child(even) {
            background-color: #f7f9fc;
        }

        .status-pending {
            color: #ff9800;
            background-color: #fff8e1;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }

        .status-paid {
            color: #4caf50;
            background-color: #e8f5e9;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }

        .status-canceled {
            color: #f44336;
            background-color: #ffebee;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }

        .status-refunded {
            color: #9c27b0;
            background-color: #f3e5f5;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }

        .order-table a {
            color: #2196f3;
            text-decoration: none;
        }

        .order-table a:hover {
            text-decoration: underline;
        }

        .order-table td:nth-child(3),
        .order-table td:nth-child(4) {
            text-align: center;
        }
        .status-icon {
            width: 16px;
            height: 16px;
            vertical-align: middle;
            margin-right: 4px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            margin: 100px auto;
            padding: 10px;
            width: fit-content;
        }

        .pagination button {
            padding: 10px 16px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 6px;
            transition: all 0.2s ease;
            font-size: 14px;
        }

        .pagination button:hover:not(.active) {
            border-color: #3480e2;
            color: #3480e2;
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .pagination button.active {
            background: #3480e2;
            color: white;
            border-color: #3480e2;
            font-weight: 500;
        }

        .pagination #pageInfo {
            padding: 0 15px;
            color: #666;
            font-size: 14px;
        }

        /* 订单详情模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 30px;
            border-radius: 12px;
            width: 80%;
            max-width: 800px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
            position: relative;
        }
        .modal-header {
            padding-bottom: 20px;
            border-bottom: 1px solid #f0f0f0;
            margin-bottom: 25px;
        }
        .modal-title {
            margin: 0;
            font-size: 22px;
            color: #2c3e50;
            font-weight: 600;
        }
        .modal-body {
            margin-bottom: 25px;
        }
        .detail-item {
            margin-bottom: 18px;
            line-height: 1.8;
            padding: 12px 15px;
            border-radius: 8px;
            transition: background-color 0.2s;
        }
        .detail-item:nth-child(even) {
            background-color: #f9fafc;
        }
        .detail-item:hover {
            background-color: #f5f7fa;
        }
        .detail-label {
            display: inline-block;
            width: 130px;
            color: #667580;
            font-weight: 500;
            font-size: 14px;
        }
        .detail-value {
            color: #2c3e50;
            font-size: 15px;
            word-break: break-word;
        }
    </style>
</head>
<body>
<div id="header"></div>
<div class="search-container">
    <div class="search-item">
        <label for="startDate">开始日期:</label>
        <input type="date" id="startDate" name="startDate">
    </div>
    <div class="search-item">
        <label for="endDate">结束日期:</label>
        <input type="date" id="endDate" name="endDate">
    </div>
    <div class="search-item">
        <label for="orderNo">订单号:</label>
        <input type="text" id="orderNo" name="orderNo" placeholder="请输入订单号">
    </div>
    <button class="btn-search" onclick="searchOrders()">查询</button>
    <button class="btn-reset" onclick="resetSearch()">重置</button>
</div>

<table class="order-table">
    <thead>
    <tr>
        <th style="width: 20%;">订单号</th>
        <th style="width: 20%;">下单时间</th>
        <th style="width: 20%; text-align: right;">金额(元)</th>
        <th style="width: 20%;">订单状态</th>
        <th style="width: 20%;">操作</th>
    </tr>
    </thead>
    <tbody id="orderList">
    <!-- 订单数据将通过Vue渲染 -->
    </tbody>
</table>

<div class="pagination">
    <button onclick="changePage(1)">首页</button>
    <button onclick="changePage(currentPage - 1)">上一页</button>
    <span id="pageInfo">第 <span id="currentPage">1</span> 页 / 共 <span id="totalPages">0</span> 页</span>
    <button onclick="changePage(currentPage + 1)">下一页</button>
    <button onclick="changePage(totalPages)">末页</button>
</div>

<script src="/home/js/jquery-3.5.1.js"></script>
<script>
    $(function () {
        $('#header').load('/home/header.html', function (response, status, xhr) {
            if (status === 'error') {
                console.error('头部加载失败: ' + xhr.status + ' ' + xhr.statusText);
            }
        });
        $('#footer').load('/home/footer.html', function (response, status, xhr) {
            if (status === 'error') {
                console.error('页脚加载失败: ' + xhr.status + ' ' + xhr.statusText);
            }
        });
    });
</script>
<script>
    let currentPage = 1;
    let totalPages = 0;
    const pageSize = 10;

    function searchOrders() {
        const startTime = document.getElementById('startDate').value;
        const endTime = document.getElementById('endDate').value;
        const orderId = document.getElementById('orderNo').value;
        const userId = localStorage.getItem('USER_ID');

        if (!userId) {
            alert('请先登录');
            return;
        }

        // 重置为第一页
        currentPage = 1;
        loadOrders(startTime, endTime, orderId, currentPage, pageSize, userId);
    }

    function changePage(page) {
        if (page < 1 || page > totalPages) return;
        currentPage = page;
        searchOrders();
    }

    function loadOrders(startTime, endTime, orderId, page, size, userId) {
        axios.get('/home/getHistoryOrderList', {
            params: {
                page: page,
                pageSize: size,
                userId: userId,
                startTime: startTime,
                endTime: endTime,
                orderId: orderId
            }
        }).then(response => {
            console.log('API响应数据:', response.data);
            if (response.data.code === 200) {
                const pageInfo = response.data.data;
                console.log('分页信息:', pageInfo);
                totalPages = pageInfo.pages || 0;
                document.getElementById('currentPage').textContent = currentPage;
                document.getElementById('totalPages').textContent = totalPages;

                // 渲染订单列表
                const orderList = document.getElementById('orderList');
                orderList.innerHTML = '';

                if (!pageInfo.list || pageInfo.list.length === 0) {
                    const emptyRow = document.createElement('tr');
                    emptyRow.innerHTML = '<td colspan="5" style="text-align: center;">暂无订单数据</td>';
                    orderList.appendChild(emptyRow);
                    return;
                }

                pageInfo.list.forEach(order => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                            <td>${order.orderId}</td>
                            <td>${formatDate(order.createTime)}</td>
                            <td style="text-align: right;">￥${order.orderPrice.toFixed(2)}</td>
                            <td><span class="status-${getStatusClass(order.orderStatus)}">${getStatusText(order.orderStatus)}</span></td>
                            <td><a href="javascript:showOrderDetail('${order.orderId}')" class="view-details">查看详情</a></td>
                        `;
                    orderList.appendChild(row);
                });
            }
        }).catch(error => {
            console.error('加载订单失败:', error);
            if (error.response) {
                alert(`API请求失败: ${error.response.status} - ${JSON.stringify(error.response.data)}`);
            } else if (error.request) {
                alert('未收到API响应，请检查网络连接');
            } else {
                alert('请求错误: ' + error.message);
            }
            alert('加载订单失败，请重试');
        });
    }

    function getStatusText(status) {
        const statusMap = {
            0: '待支付',
            1: '已支付',
            2: '已取消',
            3: '退票'
        };
        return statusMap[status] || '未知状态';
    }

    // 页面加载时默认加载第一页数据
    window.onload = function () {
        searchOrders();
    };

    function formatDate(dateString) {
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    }

    function getStatusClass(status) {
        switch(status) {
            case 0: return 'pending';
            case 1: return 'paid';
            case 2: return 'canceled';
            case 3: return 'refunded';
            default: return '';
        }
    }

    function resetSearch() {
        document.getElementById('startDate').value = '';
        document.getElementById('endDate').value = '';
        document.getElementById('orderNo').value = '';
    }
</script>
<div id="footer"></div>

<!-- 订单详情模态框 -->
<div id="orderDetailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">订单详情</h2>
            <span class="modal-close" onclick="closeModal()">&times;</span>
        </div>
        <div class="modal-body" id="modalBody">
            <!-- 订单详情内容将动态填充 -->
        </div>
    </div>
</div>

<script>
let stationMap = {};

// 获取车站列表并缓存
function getStationList() {
    if (Object.keys(stationMap).length > 0) {
        return Promise.resolve(stationMap);
    }
    return axios.get('/admin/train_number/findStationList')
        .then(response => {
            if (response.data.code === 200) {
                const stations = response.data.data;
                stations.forEach(station => {
                    stationMap[station.stationId] = station.stationName;
                });
            }
            return stationMap;
        })
        .catch(error => {
            console.error('获取车站列表失败:', error);
            return stationMap;
        });
}

function showOrderDetail(orderId) {
    // 先获取车站列表，再处理订单详情
    getStationList().then(() => {
        axios.get('/home/order/getOrderInfo', {
            params: { orderId: orderId }
        }).then(response => {
            if (response.data.code === 200) {
                const order = response.data.data;
                const modalBody = document.getElementById('modalBody');
                // 获取车站名称，默认显示ID
                const startStationName = stationMap[order.ticket.startStationId] || order.ticket.startStationId;
                const arrivalStationName = stationMap[order.ticket.arrivalStationId] || order.ticket.arrivalStationId;
                modalBody.innerHTML = `
                    <div class="detail-item">
                        <span class="detail-label">订单号:</span>
                        <span class="detail-value">${order.orderId}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">下单时间:</span>
                        <span class="detail-value">${formatDate(order.createTime)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">支付时间:</span>
                        <span class="detail-value">${order.payTime ? formatDate(order.payTime) : '未支付'}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">金额:</span>
                        <span class="detail-value">￥${order.orderPrice.toFixed(2)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">订单状态:</span>
                        <span class="detail-value"><span class="status-${getStatusClass(order.orderStatus)}">${getStatusText(order.orderStatus)}</span></span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">车次:</span>
                        <span class="detail-value">${order.ticket.trainNumberId || '未知'}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">出发站:</span>
                        <span class="detail-value">${startStationName}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">到达站:</span>
                        <span class="detail-value">${arrivalStationName}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">出发时间:</span>
                        <span class="detail-value">${formatDate(order.ticket.departureTime)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">到达时间:</span>
                        <span class="detail-value">${formatDate(order.ticket.arrivalTime)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">乘客信息:</span>
                        <span class="detail-value">
                            ${order.orderPassengerDTOList && order.orderPassengerDTOList.length > 0 ? 
                                order.orderPassengerDTOList.map(p => `
                                    ${p.passengerName} (身份证: ${p.idCard}), 车厢: ${p.carriageNumber}, 座位: ${p.seatNumber}
                                `).join('<br>') : '未填写'}
                        </span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">联系电话:</span>
                        <span class="detail-value">${order.contactPhone || '未填写'}</span>
                    </div>
                `;
                document.getElementById('orderDetailModal').style.display = 'block';
            } else {
                alert('获取订单详情失败: ' + (response.data.message || '未知错误'));
            }
        }).catch(error => {
            console.error('获取订单详情失败:', error);
            alert('获取订单详情失败，请重试');
        });
    });
}

    function closeModal() {
        document.getElementById('orderDetailModal').style.display = 'none';
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('orderDetailModal');
        if (event.target === modal) {
            closeModal();
        }
    }
    </script>
</body>
</html>